package com.gaoyuzhe.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.gaoyuzhe.entities.Payment;
import com.gaoyuzhe.lb.LoadBalancer;
import com.gaoyuzhe.to.ReturnValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author gaoyuzhe
 */
@RestController
public class OrderController {
    private static String PAYMENT_URL = "http://CLOUD-PROVIDER-PAYMENT/payment";

    @Autowired
    private LoadBalancer loadBalancer;
    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;
    @GetMapping("/consumer/insert")
    public ReturnValue<Integer> insert(Payment payment) {
       return  restTemplate.postForObject(PAYMENT_URL+"/insert",payment,ReturnValue.class);
    }

    @GetMapping("/consumer/get/{id}")
    public ReturnValue<Payment> getPayementById(@PathVariable Long id) {
        return  restTemplate.getForObject(PAYMENT_URL+"/get/"+id,ReturnValue.class);

    }

    @GetMapping("/consumer/getEntity/{id}")
    public ReturnValue<Payment> getEntityById(@PathVariable Long id) {
        ResponseEntity<ReturnValue> entity = restTemplate.getForEntity(PAYMENT_URL + "/get/" + id, ReturnValue.class);
        if(entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }
        return new ReturnValue<Payment>(444,"操作失败！");

    }


    @GetMapping("/consumer/lb")
    public String lb() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
        if(CollectionUtil.isEmpty(instances)){
            return null;
        }
        ServiceInstance loadBalanceInstance = loadBalancer.getLoadBalanceInstance(instances);
        return  restTemplate.getForObject(loadBalanceInstance.getUri() + "/payment/lb", String.class);
    }

    @GetMapping("/consumer/zipkin")
    public ReturnValue<String> zipkin() {
        ResponseEntity<ReturnValue> entity = restTemplate.getForEntity(PAYMENT_URL + "/zipkin/", ReturnValue.class);
        if(entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }
        return new ReturnValue<String>(444,"操作失败！");
    }
}
